package cn.loan.service.impl;

import cn.loan.dao.IdCardMapper;
import cn.loan.entity.IdCard;
import cn.loan.entity.User;
import cn.loan.service.IdCardService;
import cn.loan.tools.FastDfsTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: MaoSuyu
 * @User：John
 * @Date: 2019/5/14
 * @Time: 20:29
 * @Description: No Description
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class IdCardServiceImpl implements IdCardService {

    @Autowired
    private IdCardMapper idCardMapper;

    @Override
    public boolean add(MultipartFile positive, MultipartFile back, User user) throws Exception {
        //得到身份证正面的文件类型
        final String positiveFileType = positive.getOriginalFilename().substring(positive.getOriginalFilename().lastIndexOf(".") + 1);
        //得到身份证反面的文件类型
        final String backFileType = back.getOriginalFilename().substring(back.getOriginalFilename().lastIndexOf(".") + 1);
        //存储正面照到FastDFS并拿到ID
        final String idCardPositiveUrl = FastDfsTool.save1(positive.getBytes(), positiveFileType, null);
        //存储反面照到FastDFS并拿到ID
        final String idCardBackUrl = FastDfsTool.save1(back.getBytes(), backFileType, null);
        //拿到用户ID
        final int userId = user.getUser_id();
        //对信息进行封装
        IdCard idCard = new IdCard(userId, idCardPositiveUrl, idCardBackUrl);
        final int insert = idCardMapper.insert(idCard);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean findIdCardExist(User user) {
        return idCardMapper.selectCountByUserId(user.getUser_id()) > 0 ? true : false;
    }

    @Override
    public boolean del(User user) {
        final int userId = user.getUser_id();
        //查询数据
        final IdCard idCard = idCardMapper.selectIdCardByUserId(userId);
        if (null != idCard) {
            //删除正面
            final boolean delPositiveStatus = FastDfsTool.delete(idCard.getIdcard_positive()) == 0 ? true : false;
            //删除反面
            final boolean delBackStatus = FastDfsTool.delete(idCard.getIdcard_back()) == 0 ? true : false;
            //删除数据库中的数据
            final boolean deleteStatus = idCardMapper.delete(userId) > 0 ? true : false;
            if (delPositiveStatus && delBackStatus && deleteStatus) {
                return true;
            }
        }
        return false;
    }

    @Override
    public IdCard findIdCard(User user) {
        final int userId = user.getUser_id();
        return idCardMapper.selectIdCardByUserId(userId);
    }


}
